package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.flow.util.FlowUpdateAuditUtil;
import com.softer.wxzj.common.flow.util.Result;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseRegionInfoService;
import com.softer.wxzj.service.BaseSubRegionInfoService;
import com.softer.wxzj.service.OrgRegionService;
import com.softer.wxzj.service.ZoneCodeService;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:小区基本信息接口实现类
 * @ClassName: BaseRegionInfoServiceImpl
 * @author: youmingke
 * @date: 2019-05-20 16:33
 */
@Service
public class BaseRegionInfoServiceImpl implements BaseRegionInfoService {
    @Autowired
    private BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    private BaseOrganizationMapper baseOrganizationMapper;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private FlowUpdateAuditUtil flowUpdateAuditUtil;
    @Autowired
    private Result result;
    @Autowired
    private OperUtil zoneCodeUtil;
    @Autowired
    private ModifyUtil<BaseRegionInfo> modifyUtil;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private ZoneCodeService zoneCodeService;
    @Autowired
    private BaseSubRegionInfoMapper baseSubRegionInfoMapper;
    @Autowired
    private ZoneCodeMapper zoneCodeMapper;
    @Autowired
    private CombineEntityUtil<BaseRegionInfo> combineEntityUtil;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private BaseOwnerCommitteeMapper baseOwnerCommitteeMapper;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private BaseCellInfoMapper baseCellInfoMapper;
    @Autowired
    private BaseSubRegionInfoService baseSubRegionInfoService;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private BaseModifyDetailServiceImpl baseModifyDetailService;
    @Autowired
    private SysOperatorMapper sysOperatorMapper;
    @Autowired
    private OrgRegionService orgRegionService;

    private final String ID = "id";
    private final String AREA = "区";

    @Override
    public PageInfo<BaseRegionInfo> getAuditList(Page page, BaseRegionInfo baseRegionInfo) {
        //查询业务   新增审核
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.REGION_INFO_ADD.getType());
        List<BaseRegionInfo> list = new ArrayList<>();
        if (null != map) {
            result.selectParm(map, baseRegionInfo);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = baseRegionInfoMapper.getListSubmit(baseRegionInfo);
            list.forEach(x -> {
                x.setZoneCode(zoneCodeMapper.getZoneName(x.getZoneCode()));
            });
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CommonResult addAudit(String id, String opinion, String mark) {
        int i = NumberEnum.ZERO.getNum();
        String auditState = flowAddAuditUtil.audit(id, opinion, mark,null);
        if (null != auditState) {
            i = NumberEnum.ONE.getNum();
            //不在审核中则更新业务表
            if (!FlowStateEnum.IN_AUDIT.getState().equals(auditState)) {
                BaseRegionInfo baseRegionInfo = new BaseRegionInfo();
                baseRegionInfo.setId(id);
                baseRegionInfo.setRecDate(DateUtils.getNow());
                baseRegionInfo.setRecOper(ShiroUserUtil.getUserName());
                result.result(auditState, baseRegionInfo);
                i = baseRegionInfoMapper.update(baseRegionInfo);
            }
            if (FlowStateEnum.PASS.getState().equals(auditState)) {
                //小区审核通过后，判断小区是否选择了物业公司，如果选择了，则在物业公司主账号下，加入该小区的管辖权
                BaseRegionInfo info = getInfoById(id, null);
                dealBaseRegionInfo(info);

            }
        }
        return CommonResult.ResponseResult(i);
    }

    /**
     * 小区审核通过后，判断小区是否选择了物业公司，
     * 如果选择了，则在物业公司主账号下，加入该小区的管辖权
     *
     * @param info 小区信息
     */
    private void dealBaseRegionInfo(BaseRegionInfo info) {
        if (StringUtils.isNotEmpty(info.getPropertyNo())) {
            //查询物业公司主账号
            String operator = sysOperatorMapper.getMainOperatorByCompanyId(info.getId());
            OrgRegion orgRegion = new OrgRegion();
            orgRegion.setOperNo(operator);
            orgRegion.setRegionId(info.getId());
            orgRegion.setCreater(ShiroUserUtil.getUserName());
            orgRegionService.addOrgRegion(orgRegion);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult modifyAudit(String id, String opinion, String mark) {
        int num = NumberEnum.ZERO.getNum();
        //查询业务id   注意区分id
        String businessId = baseModifyReqMapper.getBusinessId(id);
        if (StringUtils.isNotBlank(businessId)) {
            String auditState = flowUpdateAuditUtil.audit(businessId, opinion, mark);
            if (null != auditState) {
                num = NumberEnum.ONE.getNum();
                //终审成功，修改业务表    其他状态不做处理
                if (FlowStateEnum.PASS.getState().equals(auditState)) {
                    //查询数据库原数据
                    BaseRegionInfo info = baseRegionInfoMapper.getInfo(businessId);
                    //将变更记录表字段更新至业务表
                    Map<String, Object> map = modifyUtil.getMap(id);
                    BaseRegionInfo base = new BaseRegionInfo();
                    base.setRegionName(info.getRegionName());
                    base.setZoneCode(info.getZoneCode());
                    //修改小区数据
                    BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getChangeColumn(map);
                    if (baseRegionInfo != null) {
                        //变更值合并到原数据
                        BaseRegionInfo completeEntity = modifyUtil.getCompleteEntity(id, info);
                        updateHouseSite(completeEntity, base);
                        num = baseRegionInfoMapper.update(baseRegionInfo);
                        //全表更新
                        num = baseRegionInfoMapper.updateById(completeEntity);
                        //修改自然幢位置
                        BaseRegionInfo baseRegionInfo1 = baseRegionInfoMapper.getInfo(businessId);
                        List<BaseBuildInfo> baseBuildInfos = baseBuildInfoMapper.selectByRegionNo(businessId);
                        if (!baseBuildInfos.isEmpty()) {
                            for (BaseBuildInfo b : baseBuildInfos) {
                                baseBuildInfoMapper.updateZoneCode(b.getId(), baseRegionInfo1.getZoneCode());
                            }
                        }
                        //修改自然妆的开发企业物业企业
                        changeBuildDepAndEvn(id, businessId);
                    }
                    // 更新图档
                    CommonResult result = fileService.dealPassModifyFile(id, businessId);
                    if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
                    }
                    //更新分区
                    CommonResult subResult = dealPassModifySubRegion(id, businessId);
                    if (ShiroResultEnum.FAIL.getCode() == subResult.getData()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), subResult.getMessage());
                    }
                }
            }
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 小区的物业企业和
     *
     * @param id         变更id
     * @param businessId 小区id
     */
    private void changeBuildDepAndEvn(String id, String businessId) {
        //查看有没有过变更开发企业
        BaseModifyDetail depNo = baseModifyDetailMapper.setByReqNo(id, "developNo");
        BaseRegionInfo regionInfo = baseRegionInfoMapper.getInfo(businessId);
        if (null != depNo) {
            //查询开发企业是否变更
            List<BaseBuildInfo> baseBuild = baseBuildInfoMapper.selectByRegion(businessId, depNo.getOldValue());
            if (!baseBuild.isEmpty()) {
                //开发企业
                List<String> lis = Arrays.asList(regionInfo.getDevelopNo().split(","));
                //修改自然幢开发企业
                baseBuildInfoMapper.updateDevelop(lis.get(0), businessId);
            }
        }
        //查看有没有过变更开发企业
        BaseModifyDetail propertyNo = baseModifyDetailMapper.setByReqNo(id, "propertyNo");
        if (null != propertyNo) {
            //查询物业企业是否变更
            List<BaseBuildInfo> baseBuild = baseBuildInfoMapper.selectByRegionPro(businessId, propertyNo.getOldValue());
            if (!baseBuild.isEmpty()) {
                //物业企业
                List<String> lis = Arrays.asList(regionInfo.getPropertyNo().split(","));
                //修改自然幢物业企业
                baseBuildInfoMapper.updateEnviron(lis.get(0), businessId);
            }
        }
    }

    @Override
    public CommonResult submitAudit(String id) {
        //调用增加方法
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(id);
        if ((NumStrEnum.ONE.getNum()).equals(baseRegionInfo.getSubRegionFlag())) {
            int no = baseSubRegionInfoMapper.selectRegion(id);
            if (no == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "未添加分区，无法提交");
            }
        }
        baseRegionInfo.setFlowState(NumStrEnum.ONE.getNum());
        int num = baseRegionInfoMapper.update(baseRegionInfo);
        //若不失败，进入审批流
        if (num > 0) {
            String initState = flowAddAuditUtil.initFlow(baseRegionInfo.getId(), FlowTypeEnum.REGION_INFO_ADD.getType(), null);
            //判断返回值状态   当为2时更新业务表
            if (StringUtils.isNotBlank(initState)) {
                baseRegionInfo.setFlowState(initState);
                if (("2").equals(initState)){
                    baseRegionInfo.setRecDate(DateUtils.getNow());
                }
                num = baseRegionInfoMapper.update(baseRegionInfo);
            }
            if (num == 0) {
                return new CommonResult(ShiroResultEnum.FAIL.getCode(), "操作失败");
            }
        }
        return CommonResult.ResponseResult(num);
    }

    private int changedep(String baseRegionInfo, String oldBaseRegionInfo, String id, int q) {
        int num;
        if (null != baseRegionInfo && baseRegionInfo != "") {
            if (null != oldBaseRegionInfo && oldBaseRegionInfo != "") {
                String[] oldList = oldBaseRegionInfo.split(",");
                String[] newList = baseRegionInfo.split(",");
                Arrays.sort(oldList);
                Arrays.sort(newList);

                if (oldBaseRegionInfo.indexOf(",") < 0) {
                    if (baseRegionInfo.indexOf(",") < 0) {
                        boolean a = Arrays.equals(oldList, newList);
                        if (a == false) {
                            List list = Arrays.asList(oldList);
                            Set set = new HashSet(list);
                            String[] rid = (String[]) set.toArray(newList);
                            String str2 = ArrayUtils.toString(rid, ",");
                            if (q == 0) {
                                num = baseBuildInfoMapper.selectCountDeve(str2, id);
                            } else {
                                num = baseBuildInfoMapper.selectCountenv(str2, id);
                            }
                            return num;
                        }
                    }
                }
                num = oldBaseRegionInfo.compareTo(baseRegionInfo);
                if (num != 0) {
                    List list = Arrays.asList(oldList);
                    Set set = new HashSet(list);
                    String[] rid = (String[]) set.toArray(newList);
                    String str2 = ArrayUtils.toString(rid, ",");
                    if (q == 0) {
                        num = baseBuildInfoMapper.selectCountDeve(str2, id);
                    } else {
                        num = baseBuildInfoMapper.selectCountenv(str2, id);
                    }
                }
            } else {
                num = 0;
            }
        } else {
            if (q == 0) {
                num = baseBuildInfoMapper.selectCountDeve(oldBaseRegionInfo, id);
            } else {
                num = baseBuildInfoMapper.selectCountenv(oldBaseRegionInfo, id);
            }
        }
        return num;
    }

    /**
     * 小区信息变更
     *
     * @param baseRegionInfo 小区信息
     * @return 变更结果
     * @throws Exception 异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult modify(BaseRegionInfo baseRegionInfo) throws Exception {
        String id = baseRegionInfo.getId();
        BaseRegionInfo oldBaseRegionInfo = baseRegionInfoMapper.getModifyInfo(id);
        //获取原始业务数据   2审批通过：可变更
        String deve = baseRegionInfo.getDevelopNo();
        String deveOld = oldBaseRegionInfo.getDevelopNo();
        String prop = baseRegionInfo.getPropertyNo();
        String propOld = oldBaseRegionInfo.getPropertyNo();
        int a = changedep(deve, deveOld, id, 0);
        if (a != 0) {
            return CommonResult.ResponseResult(0, "开发企业已经被使用");
        }
        int b = changedep(prop, propOld, id, 1);
        if (b != 0) {
            return CommonResult.ResponseResult(0, "物业企业已经被使用");
        }
        //变更类型表id    注意区分id!!
        String uuid = UUIDUtil.getUUID();
        //赋初始值，防止变更flowState
        baseRegionInfo.setFlowState(String.valueOf(NumberEnum.TWO.getNum()));
        baseRegionInfo.setModifier(oldBaseRegionInfo.getModifier());
        baseRegionInfo.setCreater(oldBaseRegionInfo.getCreater());
        baseRegionInfo.setState(oldBaseRegionInfo.getState());
        baseRegionInfo.setRegionNo(oldBaseRegionInfo.getRegionNo());
        String modifyType = baseRegionInfo.getModifyType();
        String modifyCause = baseRegionInfo.getModifyCause();
        int num = modifyUtil.updateToSave(oldBaseRegionInfo, baseRegionInfo, id, modifyType, modifyCause, uuid);
        if (num == NumberEnum.MINUS_ONE.getNum()) {
            num = 0;
        }
        // 图档变更操作
        int count = fileService.modifyFile(baseRegionInfo.getFileTypeList(), id, modifyType, modifyCause, uuid);
        int modifyNum = 0;
        if (NumStrEnum.ONE.getNum().equals(baseRegionInfo.getSubRegionFlag())) {
            List<BaseSubRegionInfo> baseSubRegionList = baseRegionInfo.getBaseSubRegionList();
            //如果有分区， 分区的变更处理
            if (baseSubRegionList != null && !baseSubRegionList.isEmpty()) {
                List<String> nameList = baseSubRegionList.stream().map(p -> p.getSubRegionName().endsWith(AREA) ? p.getSubRegionName() : (p.getSubRegionName() + AREA)).collect(Collectors.toList());
                List<String> noList = baseSubRegionList.stream().map(p -> p.getSubRegionNo()).collect(Collectors.toList());
                for (String name : nameList) {
                    int frequency = Collections.frequency(nameList, name);
                    if (frequency > 1) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), name + ":分区名称已存在");
                    }
                }
                for (String no : noList) {
                    int frequency = Collections.frequency(noList, no);
                    if (frequency > 1) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), no + ":分区编号已存在");
                    }
                }
                modifyNum = subRegionModify(baseRegionInfo.getBaseSubRegionList(), baseRegionInfo, uuid);
            }
        }
        if ((num + count + modifyNum) <= NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败！请检查变更数据！");
        }
        //绑定审批流
        String initState = flowUpdateAuditUtil.initFlow(id, uuid, FlowTypeEnum.REGION_INFO_MODIFY.getType(), null);
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        if (FlowStateEnum.PASS.getState().equals(initState)) {
            //查询数据库原数据
            BaseRegionInfo info = baseRegionInfoMapper.getInfo(id);
            //修改房屋数据
            updateHouseSite(baseRegionInfo, info);
            //变更值合并到原数据   注意参数：uuid变更类型id   info数据库实体
            BaseRegionInfo completeEntity = modifyUtil.getCompleteEntity(uuid, info);
            //全表更新
            num = baseRegionInfoMapper.updateById(completeEntity);
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败！请检查变更数据！");
            }
            //修改自然幢位置
            List<BaseBuildInfo> baseBuildInfos = baseBuildInfoMapper.selectByRegionNo(id);
            if (!baseBuildInfos.isEmpty()) {
                for (BaseBuildInfo base : baseBuildInfos) {
                    baseBuildInfoMapper.updateZoneCode(base.getId(), baseRegionInfo.getZoneCode());
                }
            }
            //修改自然幢开发企业和物业企业
            changeBuildDepAndEvn(uuid, id);
            // 更新图档
            CommonResult result = fileService.dealPassModifyFile(uuid, id);
            if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
            }
            //更新分区
            CommonResult subResult = dealPassModifySubRegion(uuid, id);
            if (ShiroResultEnum.FAIL.getCode() == subResult.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), subResult.getMessage());
            }
        }
        return CommonResult.ResponseResult(num + count + modifyNum);
    }

    /**
     * 处理变更审核通过后的分区处理
     *
     * @param id         变更的ID
     * @param businessId 小区ID
     * @return 处理结果
     */
    private CommonResult dealPassModifySubRegion(String id, String businessId) {
        // 更新分区
        //获取删除的分区ID集合
        List<String> delBusinessIdList = baseModifyDetailMapper.getDelBusinessId(id);
        if (!delBusinessIdList.isEmpty()) {
            String delId = String.join(",", delBusinessIdList);
            int num = baseSubRegionInfoMapper.updateDelSupRegion(delId);
            if (num <= NumberEnum.ZERO.getNum()) {
                return CommonResult.ResponseResult(num);
            }
        }
        //处理新增的分区ID集合
        List<String> addBusinessIdList = baseModifyDetailMapper.getAddBusinessId(id);
        if (!addBusinessIdList.isEmpty()) {
            String addId = String.join(",", addBusinessIdList);
            List<BaseSubRegionInfo> list = baseModifyDetailMapper.getAddBaseSubRegion(id, addId);
            for (BaseSubRegionInfo baseSubRegionInfo : list) {
                baseSubRegionInfo.setRegionNo(businessId);
                int insert = baseSubRegionInfoMapper.insert(baseSubRegionInfo);
                if (insert <= NumberEnum.ZERO.getNum()) {
                    return CommonResult.ResponseResult(insert);
                }
            }
        }
        //处理修改的分区
        List<String> modifyBusinessId = baseModifyDetailMapper.getModifyBusinessId(id);
        if (!modifyBusinessId.isEmpty()) {
            String modifyId = String.join(",", modifyBusinessId);
            List<BaseSubRegionInfo> modifyBaseSubRegion = baseModifyDetailMapper.getModifyBaseSubRegion(id, modifyId);
            for (BaseSubRegionInfo baseSubRegionInfo : modifyBaseSubRegion) {
                int num = baseSubRegionInfoMapper.updateByCondition(baseSubRegionInfo);
                if (num <= NumberEnum.ZERO.getNum()) {
                    return CommonResult.ResponseResult(num);
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 处理分区变更
     *
     * @param baseSubRegionList 分区集合
     * @param baseRegionInfo    小区信息
     * @param uuid              变更Id
     * @return 变更结果
     */
    private int subRegionModify(List<BaseSubRegionInfo> baseSubRegionList, BaseRegionInfo baseRegionInfo, String uuid) throws Exception {
        //分区不为空
        BaseSubRegionInfo baseSubRegionInfo = new BaseSubRegionInfo();
        baseSubRegionInfo.setRegionNo(baseRegionInfo.getId());
        //查询原始分区数据
        List<BaseSubRegionInfo> allList = baseSubRegionInfoService.getAllList(baseSubRegionInfo);
        //在变更后中存在的，在原始数据中不存在的分区(新增的分区)
        List<BaseSubRegionInfo> newList = baseSubRegionList.stream().filter(item -> !allList.stream().map(e -> e.getId())
                .collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());
        //在变更后中不存在的，在原始数据中存在的分区（删除的分区）
        List<BaseSubRegionInfo> oldList = allList.stream().filter(item -> !baseSubRegionList.stream().map(e -> e.getId())
                .collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());
        //变更前后都存在的分区集合（修改的分区）(修改后的数据)
        List<BaseSubRegionInfo> commonAfterList = baseSubRegionList.stream().filter(item -> allList.stream().map(e -> e.getId())
                .collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());
        //变更前后都存在的分区集合（修改的分区）(修改前的数据)
        List<BaseSubRegionInfo> commonBeforeList = allList.stream().filter(item -> baseSubRegionList.stream().map(e -> e.getId())
                .collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());
        return dealSubRegionList(newList, oldList, commonAfterList, commonBeforeList, baseRegionInfo, uuid);
    }

    /**
     * 处理变更的分区信息
     *
     * @param newList          在变更后中存在的，在原始数据中不存在的分区(新增的分区)
     * @param oldList          在变更后中不存在的，在原始数据中存在的分区（删除的分区）
     * @param commonAfterList  变更前后都存在的分区集合（修改的分区）(修改后的数据)
     * @param commonBeforeList 变更前后都存在的分区集合（修改的分区）(修改前的数据)
     * @param baseRegionInfo   小区信息
     * @param uuid             变更Id
     */
    private int dealSubRegionList(List<BaseSubRegionInfo> newList, List<BaseSubRegionInfo> oldList, List<BaseSubRegionInfo> commonAfterList, List<BaseSubRegionInfo> commonBeforeList, BaseRegionInfo baseRegionInfo, String uuid) throws Exception {
        //处理新增的分区
        int i = dealList(newList, uuid, 1);
        //处理删除的分区
        int num = dealList(oldList, uuid, 0);
        //处理修改的分区
        int count = dealCommonList(commonAfterList, commonBeforeList);
        if ((i + num + count) > 0) {
            //有修改的项目
            //查询base_modify_req表中是否存在变更记录，不存在，则新增一条
            int reqNum = baseModifyReqMapper.selectCountId(uuid);
            if (reqNum == 0) {
                reqNum = modifyUtil.saveModifyReq(uuid, baseRegionInfo.getId(), baseRegionInfo.getModifyType(), baseRegionInfo.getModifyCause(), ShiroUserUtil.getUserName());
                if (reqNum == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "新增变更记录失败");
                }
            }
        }
        return i + num + count;
    }

    /**
     * 处理修改的分区
     *
     * @param commonAfterList  修改后的分区集合
     * @param commonBeforeList 修改前的分区集合
     * @return 修改结果
     * @throws Exception 异常
     */
    private int dealCommonList(List<BaseSubRegionInfo> commonAfterList, List<BaseSubRegionInfo> commonBeforeList) throws Exception {
        int num = 0;
        //处理修改的分区
        for (BaseSubRegionInfo baseSubRegionInfo : commonAfterList) {
            for (BaseSubRegionInfo b : commonBeforeList) {
                if (baseSubRegionInfo.getId().equals(b.getId())) {
                    List<BaseModifyDetail> list = GetDifferenceUtil.getDifference(b, baseSubRegionInfo);
                    if (list != null && !list.isEmpty()) {
                        num = 1;
                    }
                    for (BaseModifyDetail baseModifyDetail : list) {
                        baseModifyDetail.setCreater(ShiroUserUtil.getUserName());
                        baseModifyDetail.setBusinessId(b.getId());
                        baseModifyDetail.setId(UUIDUtil.getUUID());
                        baseModifyDetail.setType(NumStrEnum.TWO.getNum());
                        baseModifyDetailMapper.insert(baseModifyDetail);
                    }
                    break;
                }
            }
        }
        return num;
    }

    private int dealList(List<BaseSubRegionInfo> list, String uuid, int type) throws Exception {
        int num = 0;
        if (!list.isEmpty()) {
            for (BaseSubRegionInfo baseSubRegionInfo : list) {
                addModifyDetail(baseSubRegionInfo, uuid, type);
            }
            num = 1;
        }
        return num;
    }

    /**
     * base_modify_detail表中增加一条数据
     *
     * @param baseSubRegionInfo 分区信息
     * @param uuid              base_modify_req的ID
     * @return 新增结果
     */
    public int addModifyDetail(BaseSubRegionInfo baseSubRegionInfo, String uuid, int type) {
        List<BaseModifyDetail> list = new ArrayList<>();
        String id = baseSubRegionInfo.getId();
        String subRegionName = baseSubRegionInfo.getSubRegionName();
        if (!subRegionName.endsWith(AREA)) {
            subRegionName += AREA;
        }
        if (StringUtils.isEmpty(id)) {
            id = UUIDUtil.getUUID();
        }
        list.add(addBaseModify(id, uuid, id, ID, "分区Id", type));
        list.add(addBaseModify(subRegionName, uuid, id, "sub_region_name", "分区名称", type));
        list.add(addBaseModify(baseSubRegionInfo.getSubRegionNo(), uuid, id, "sub_region_no", "分区编号", type));
        list.add(addBaseModify(baseSubRegionInfo.getRemark(), uuid, id, "remark", "描述", type));
        return baseModifyDetailMapper.insertList(list);
    }

    public BaseModifyDetail addBaseModify(String value, String uuid, String id, String columnName, String name, int type) {
        BaseModifyDetail base = new BaseModifyDetail();
        if (type == 0) {
            base.setOldValue(value);
        } else {
            if (ID.equals(columnName)) {
                value = id;
            }
            base.setNewValue(value);
        }
        base.setReqNo(uuid);
        base.setBusinessId(id);
        base.setCreater(ShiroUserUtil.getUserName());
        base.setColumnName(columnName);
        base.setName(name);
        return base;
    }

    @Override
    public PageInfo<BaseRegionInfo> getModifyList(Page page, BaseRegionInfo baseRegionInfo) {
        //参数验证
        if (null == baseRegionInfo || StringUtils.isBlank(baseRegionInfo.getFlowState())) {
            return null;
        }
        //赋值区域,重要
        baseRegionInfo.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        baseRegionInfo.setModifyType(FlowTypeEnum.REGION_INFO_MODIFY.getType());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> list = baseRegionInfoMapper.getModifyReqList(baseRegionInfo);

        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseRegionInfo> getModifyAuditList(Page page, BaseRegionInfo baseRegionInfo) {
        //参数验证
        if (null == baseRegionInfo || StringUtils.isBlank(baseRegionInfo.getFlowState())) {
            return null;
        }
        //查询业务
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.REGION_INFO_MODIFY.getType());
        List<BaseRegionInfo> list = new ArrayList<>();
        if (null != map) {
            result.selectParm(map, baseRegionInfo);
            baseRegionInfo.setModifyType(FlowTypeEnum.REGION_INFO_MODIFY.getType());
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = baseRegionInfoMapper.getModifyReqList(baseRegionInfo);
            list.forEach(x -> x.setZoneCode(zoneCodeMapper.getZoneName(x.getZoneCode())));
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseModifyDetail> getModifyDetailList(Page page, String id) {
        List<BaseModifyDetail> list = baseModifyDetailMapper.getListByReqId(id);
        //处理小区变更项
        dealRegionModifyList(list);
        //处理分区变更项
        dealSubRegionModify(list, id);

        PageInfo<BaseModifyDetail> pageInfo = new PageInfo<>();
        if (list != null && !list.isEmpty()) {
            pageInfo = new PageInfo<>(baseModifyDetailService.pageAll(page, list));
            pageInfo.setTotal(list.size());
        }
        return pageInfo;
    }

    /**
     * 处理分区的变更
     *
     * @param list 小区的变更集合
     * @param id   变更的Id
     */
    private void dealSubRegionModify(List<BaseModifyDetail> list, String id) {
        //获取删除的分区ID集合
        List<String> delBusinessIdList = baseModifyDetailMapper.getDelBusinessId(id);
        for (String businessId : delBusinessIdList) {
            addModifyDetailToList(list, id, businessId, "删除分区");
        }
        //处理新增的分区ID集合
        List<String> addBusinessIdList = baseModifyDetailMapper.getAddBusinessId(id);
        for (String businessId : addBusinessIdList) {
            addModifyDetailToList(list, id, businessId, "新增分区");
        }
        //处理修改的分区
        List<String> modifyBusinessId = baseModifyDetailMapper.getModifyBusinessId(id);
        for (String businessId : modifyBusinessId) {
            addModifyDetailToList(list, id, businessId, "修改分区");
        }
    }

    /**
     * 添加变更项到集合
     *
     * @param list       变更集合
     * @param id         变更ID
     * @param businessId 分区ID
     * @param name       变更项名称
     */
    public void addModifyDetailToList(List<BaseModifyDetail> list, String id, String businessId, String name) {
        BaseModifyDetail baseModifyDetail = baseModifyDetailMapper.getModifyDetail(id, businessId);
        baseModifyDetail.setName(name);
        list.add(baseModifyDetail);
    }


    /**
     * 处理小区变更项
     *
     * @param list 小区变更集合
     */
    private void dealRegionModifyList(List<BaseModifyDetail> list) {
        for (BaseModifyDetail modifyDetail : list) {
            switch (modifyDetail.getColumnName()) {
                case "subRegionFlag":
                    modifyDetail.setNewValue(NumStrEnum.ONE.getNum().equals(modifyDetail.getNewValue()) ? "是" : "否");
                    modifyDetail.setOldValue(NumStrEnum.ONE.getNum().equals(modifyDetail.getOldValue()) ? "是" : "否");
                    break;
                case "developNo":
                    String[] ids = modifyDetail.getNewValue().split(",");
                    String[] idOld = modifyDetail.getOldValue().split(",");
                    modifyDetail.setNewValue("");
                    modifyDetail.setOldValue("");
                    String oldDep = "";
                    for (String newDep : ids) {
                        //for 循环值
                        String newDevelopNo = baseOrganizationMapper.selectNameFromId(newDep);
                        String depName = null == newDevelopNo ? newDep : newDevelopNo;
                        modifyDetail.setNewValue(modifyDetail.getNewValue() + " " + depName);
                    }
                    for (String idOlds : idOld) {
                        String oldDevelopNo = baseOrganizationMapper.selectNameFromId(idOlds);
                        oldDep = null == oldDevelopNo ? idOlds : oldDevelopNo;
                        modifyDetail.setOldValue(modifyDetail.getOldValue() + " " + oldDep);
                    }
                    if (modifyDetail.getOldValue().endsWith(",")) {
                        //，若最后一个字段为，则删除，
                        String a = modifyDetail.getOldValue().substring(0, modifyDetail.getOldValue().length() - 1);
                        modifyDetail.setOldValue(a);
                    }
                    if (modifyDetail.getNewValue().endsWith(",")) {
                        String a = modifyDetail.getNewValue().substring(0, modifyDetail.getOldValue().length() - 1);
                        modifyDetail.setOldValue(a);
                    }
                    break;
                case "propertyNo":
                    //for 循环值，若最后一个字段为，则删除，
                    String[] envie = modifyDetail.getNewValue().split(",");
                    String[] oldEnvir = modifyDetail.getOldValue().split(",");
                    modifyDetail.setNewValue("");
                    modifyDetail.setOldValue("");
                    for (String envirs : envie) {
                        String newEnvironNo = baseOrganizationMapper.getConcatOrgNameByIds(envirs);
                        String en = null == newEnvironNo ? envirs : newEnvironNo;
                        modifyDetail.setNewValue(modifyDetail.getNewValue() + "" + en);
                    }
                    for (String envirs : oldEnvir) {
                        String oldEnvironNo = baseOrganizationMapper.getConcatOrgNameByIds(envirs);
                        String en = null == oldEnvironNo ? envirs : oldEnvironNo;
                        modifyDetail.setOldValue(modifyDetail.getOldValue() + "" + en);
                    }
                    if (modifyDetail.getOldValue().endsWith(",")) {
                        String a = modifyDetail.getOldValue().substring(0, modifyDetail.getOldValue().length() - 1);
                        modifyDetail.setOldValue(a);
                    }
                    if (modifyDetail.getNewValue().endsWith(",")) {
                        String a = modifyDetail.getNewValue().substring(0, modifyDetail.getOldValue().length() - 1);
                        modifyDetail.setOldValue(a);
                    }
                    break;
                case "zoneCode":
                    String newRegionCode = modifyDetail.getNewValue();
                    String oldRegionCode = modifyDetail.getOldValue();
                    ZoneCode newZoneCode = zoneCodeMapper.getInfoByZoneCode(newRegionCode);
                    ZoneCode oldZoneCode = zoneCodeMapper.getInfoByZoneCode(oldRegionCode);
                    String newName = zoneCodeService.zoneName(newZoneCode);
                    String oldName = zoneCodeService.zoneName(oldZoneCode);
                    modifyDetail.setNewValue(newName);
                    modifyDetail.setOldValue(oldName);
                    break;
            }
        }
    }

    @Override
    public CommonResult auditPass(String id) {
        BaseRegionInfo baseRegionInfo = new BaseRegionInfo();
        baseRegionInfo.setId(id);
        baseRegionInfo.setFlowState(FlowStateEnum.PASS.getState());
        baseRegionInfo.setRecOper(ShiroUserUtil.getUserName());
        baseRegionInfo.setRecDate(DateUtils.getNow());
        int num = baseRegionInfoMapper.update(baseRegionInfo);
        return CommonResult.ResponseResult(num);
    }

    /**
     * 获取小区编号
     *
     * @return 小区编号
     */
    public String getRegNo() {
        String regNo = baseRegionInfoMapper.selectMaxRegionNo();
        int regNum = 0;
        if (StringUtils.isBlank(regNo)) {
            regNo = NumStrEnum.ZERO.getNum();
            regNum = Integer.parseInt(regNo);
            String rNo = String.format("%07d", regNum);
            return NumStrEnum.ONE.getNum() + rNo;
        } else {
            regNum = Integer.parseInt(regNo);
            regNum++;
            return String.format("%07d", regNum);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult insert(BaseRegionInfo baseRegionInfo) {
        String regNo = getRegNo();
        baseRegionInfo.setRegionNo(regNo);
        String id = UUIDUtil.getUUID();
        baseRegionInfo.setId(id);
        baseRegionInfo.setCreater(ShiroUserUtil.getUserName());
        //参数转换
        baseRegionInfo.setUseArea(ParamUtil.setParam(baseRegionInfo.getUseArea()));
        baseRegionInfo.setStruArea(ParamUtil.setParam(baseRegionInfo.getStruArea()));
        //保存状态：0
        //保存状态看添加人
        if (StringUtils.isBlank(baseRegionInfo.getFlowState()) || NumStrEnum.ZERO.getNum().equals(baseRegionInfo.getFlowState())) {
            baseRegionInfo.setFlowState(NumStrEnum.ZERO.getNum());
        } else {
            //备案
            baseRegionInfo.setState(String.valueOf(NumberEnum.ONE.getNum()));
            baseRegionInfo.setRecDate(DateUtils.getNow());
            flowUtil.saveDefaultFlowInstance(UUIDUtil.getUUID(), id, FlowTypeEnum.REGION_INFO_ADD.getType(), null,null);
            dealBaseRegionInfo(baseRegionInfo);
        }
        if (StringUtils.isBlank(baseRegionInfo.getPropertyNo())) {
            baseRegionInfo.setPropertyNo(null);
        }
        if (baseRegionInfoMapper.getCountByRegionName(baseRegionInfo.getRegionName(), id) > 0) {
            return CommonResult.strResult(0, "小区名称重复！");
        }
        int i = baseRegionInfoMapper.insert(baseRegionInfo);
        if (i > NumberEnum.ZERO.getNum()) {
            //处理分区信息
            CommonResult commonResult = dealSubRegionInfo(baseRegionInfo.getBaseSubRegionList(), id);
            if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
            }
            //处理图档信息
            //保存图片
            CommonResult result = fileService.addFile(baseRegionInfo.getFileTypeList(), id);
            if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
            }
        }
        return CommonResult.idResult(i, id);
    }

    /**
     * 处理分区信息
     *
     * @param baseSubRegionList 分区集合
     */
    private CommonResult dealSubRegionInfo(List<BaseSubRegionInfo> baseSubRegionList, String id) {
        if (!baseSubRegionList.isEmpty()) {
            for (BaseSubRegionInfo subRegionInfo : baseSubRegionList) {
                subRegionInfo.setRegionNo(id);
                subRegionInfo.setCreater(ShiroUserUtil.getUser().getOperName());
                if (StringUtils.isEmpty(subRegionInfo.getId())) {
                    //ID为空，则为新增的分区
                    CommonResult insert = baseSubRegionInfoService.insert(subRegionInfo);
                    if (ShiroResultEnum.FAIL.getCode() == insert.getData()) {
                        return insert;
                    }
                } else {
                    //ID不为空，则为修改的分区
                    CommonResult update = baseSubRegionInfoService.update(subRegionInfo);
                    if (ShiroResultEnum.FAIL.getCode() == update.getData()) {
                        return update;
                    }
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 小区修改
     *
     * @param baseRegionInfo 小区信息
     * @return 修改结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult update(BaseRegionInfo baseRegionInfo) {
        BaseRegionInfo info = baseRegionInfoMapper.getInfo(baseRegionInfo.getId());
        //查询原始数据
        updateHouseSite(baseRegionInfo, info);
        //合并实体  注意参数顺序 第一个前端传   第二个数据库原始数据
        BaseRegionInfo combineEntity = combineEntityUtil.combineEntity(baseRegionInfo, info);
        //注意是全表更新
        int num = baseRegionInfoMapper.updateById(combineEntity);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //修改分区
        CommonResult commonResult = dealSubRegionInfo(baseRegionInfo.getBaseSubRegionList(), baseRegionInfo.getId());
        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
        }
        //处理图片修改
        CommonResult result = fileService.updateFile(baseRegionInfo.getFileTypeList(), baseRegionInfo.getId());
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 修改房屋的地址
     *
     * @param baseRegionInfo 新值
     * @param info           旧值
     * @return
     */
    private int updateHouseSite(BaseRegionInfo baseRegionInfo, BaseRegionInfo info) {
        //查询房屋有没有该小区若有则修改房屋的信息
        int num = 1;
        List<BaseBuildInfo> basebuild = baseBuildInfoMapper.getBuildList(baseRegionInfo.getId(), null);
        if (null != basebuild) {
            String SubRegionName = "";
            for (BaseBuildInfo baseBuildInfo : basebuild) {
                if (StringUtils.isNotBlank(baseBuildInfo.getSubRegionNo())) {
                    BaseSubRegionInfo baseSubRegionInfo = baseSubRegionInfoMapper.getInfo(baseBuildInfo.getSubRegionNo());
                    SubRegionName = baseSubRegionInfo.getSubRegionName();
                }
                List<BaseHouseInfo> house = baseHouseInfoMapper.selectAllByBuildId(baseBuildInfo.getId(), null);

                if (null != house) {
                    for (BaseHouseInfo in : house) {
                        //修改小区名称
                        if (StringUtils.isNotBlank(in.getHouseSite())) {
                            String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(info.getZoneCode(), 0, 6));
                            //修改小区名称
                            if (!baseRegionInfo.getRegionName().equals(info.getRegionName())) {
                                BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(in.getCellNo());
                                String houseSite = zoneName + baseRegionInfo.getRegionName() + SubRegionName + baseBuildInfo.getBuildName() + baseCellInfo.getCellName() + in.getRoomName();
                                num = baseHouseInfoMapper.updateHouseSite(houseSite, in.getId());
                                if (num == NumberEnum.ZERO.getNum()) {
                                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                                }
                            }
                            if (!baseRegionInfo.getZoneCode().equals(info.getZoneCode())) {
                                BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(in.getCellNo());
                                String houseSite = zoneName + baseRegionInfo.getRegionName() + SubRegionName + baseBuildInfo.getBuildName() + baseCellInfo.getCellName() + in.getRoomName();
                                num = baseHouseInfoMapper.updateHouseSite(houseSite, in.getId());
                                if (num == NumberEnum.ZERO.getNum()) {
                                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                                }
                            }
                        }
                    }
                }
            }
        }
        return num;
    }

    @Override
    public CommonResult delete(String id) {
        //查询自然幢数量
        int count = baseBuildInfoMapper.getCountByRegionNo(id);
        if (count > NumberEnum.ZERO.getNum()) {
            return CommonResult.strResult(NumberEnum.ZERO.getNum(), "已存在自然幢信息！");
        }
        count = flowInstanceMapper.getCountByBusinessId(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在审核中信息，不允许删除！");
        }
        count = baseOwnerCommitteeMapper.selectRegionNo(null, id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "业委会或居委会绑定该信息，不允许删除！");
        }
        count = baseSubRegionInfoMapper.selectRegion(id);
        if (count > 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "该小区有分区，不允许删除！");
        }
        int num = baseRegionInfoMapper.updateStateById(id, String.valueOf(NumberEnum.TWO.getNum()));
        return CommonResult.ResponseResult(num);
    }

    /**
     * 根据id获取小区基本信息详情
     *
     * @param id      小区id
     * @param arcType 图档大类
     * @return 小区信息
     */
    @Override
    public BaseRegionInfo getInfoById(String id, String arcType) {

        BaseRegionInfo info = baseRegionInfoMapper.getInfo(id);
        //查询该小区有没有业委会
        String indCouncil = baseOwnerCommitteeMapper.selectNameById(id, "05");
        //查询该小区有没有居委会
        String neighCommit = baseOwnerCommitteeMapper.selectNameById(id, "06");
        info.setIndCouncil(indCouncil);
        info.setNeighCommit(neighCommit);
        ZoneCode newZoneCode = zoneCodeMapper.getInfoByZoneCode(info.getZoneCode());
        List<BaseOrganization> pros = new ArrayList();
        List<BaseOrganization> devs = new ArrayList();
        if (StringUtils.isNotBlank(info.getPropertyNo())) {
            List<String> list = Arrays.asList(info.getPropertyNo().split(","));
            for (String pro : list) {
                BaseOrganization b = baseOrganizationMapper.getInfo(pro);
                pros.add(b);
            }
        }
        if (StringUtils.isNotBlank(info.getDevelopNo())) {
            List<String> list = Arrays.asList(info.getDevelopNo().split(","));
            for (String dev : list) {
                BaseOrganization b = baseOrganizationMapper.getInfo(dev);
                devs.add(b);
            }
        }
        info.setProList(pros);
        info.setDevList(devs);
        String superiors = zoneCodeService.zoneCodeSuperiorsAll(info.getZoneCode());
        info.setZoneCode(superiors);
        info.setZoneCodeName(zoneCodeService.zoneName(newZoneCode));
        //查询分区信息
        BaseSubRegionInfo baseSubRegionInfo = new BaseSubRegionInfo();
        baseSubRegionInfo.setRegionNo(id);
        List<BaseSubRegionInfo> list = baseSubRegionInfoMapper.getList(baseSubRegionInfo);
        info.setBaseSubRegionList(list);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
        info.setFileTypeList(fileVOList);
        return info;
    }

    @Override
    public List<BaseRegionInfo> selectCommitteByZoneCode(String zoneCode, String type) {
        List<BaseRegionInfo> baseRegionInfos = baseRegionInfoMapper.selectCommitteByZoneCode(zoneCode, type);
        return baseRegionInfos;
    }


    @Override
    public PageInfo<BaseRegionInfo> getList(Page page, BaseRegionInfo baseRegionInfo) {
        //赋值区域,重要
        baseRegionInfo.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        if ("0,3".equals(baseRegionInfo.getFlowState())) {
            String name = ShiroUserUtil.getUserName();
            baseRegionInfo.setCreater(name);
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> list = baseRegionInfoMapper.getList(baseRegionInfo);
        //区域转译
        for (int i = 0; i < list.size(); i++) {
            BaseRegionInfo b = list.get(i);
            if (StringUtils.isNotEmpty(b.getZoneCode())) {
                String zoneName = zoneCodeMapper.getZoneName(b.getZoneCode());
                b.setZoneCode(zoneName);
                list.set(i, b);
            }
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public BaseRegionInfo getInfo(String id) {
        return null;
    }

    @Override
    public BaseRegionInfo getInfoById(String id) {
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfoById(id);
        //查询该小区有没有业委会
        String indCouncil = baseOwnerCommitteeMapper.selectNameById(id, "05");
        //查询该小区有没有居委会
        String neighCommit = baseOwnerCommitteeMapper.selectNameById(id, "06");
        baseRegionInfo.setIndCouncil(indCouncil);
        baseRegionInfo.setNeighCommit(neighCommit);
        return baseRegionInfo;
    }

    @Override
    public PageInfo<FunBalInfo> selectOwnerFunBal(Page page, String fuzzy) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<FunBalInfo> list = baseRegionInfoMapper.selectOwnerFunBal(fuzzy);
        PageInfo<FunBalInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<BaseOrganization> getOrgList(String id, String orgTypeCode) {
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(id);
        if (null == baseRegionInfo) {
            return null;
        }
        BaseOrganization organization = new BaseOrganization();
        // 01开发公司   02物业企业
        if ("01".equals(orgTypeCode)) {
            organization.setId(baseRegionInfo.getDevelopNo());
        } else if ("02".equals(orgTypeCode)) {
            organization.setId(baseRegionInfo.getPropertyNo());
        }
        return baseOrganizationMapper.getList(organization);
    }

    /**
     * 小区名称
     *
     * @return
     */
    @Override
    public List<BaseRegionInfo> selectRegion() {
        return baseRegionInfoMapper.selectRegion();
    }

    /**
     * 模糊查询建档小区信息列表
     *
     * @param baseRegionInfo 模糊查询参数
     * @return 小区信息
     */
    @Override
    public PageInfo<BaseRegionInfo> fuzzySearch(Page page, BaseRegionInfo baseRegionInfo) {
        //查询业务
        baseRegionInfo.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (("0,3").equals(baseRegionInfo.getFlowState())) {
            String name = ShiroUserUtil.getUserName();
            baseRegionInfo.setCreater(name);
        }
        List<BaseRegionInfo> list = baseRegionInfoMapper.fuzzySearchByParam(baseRegionInfo);

        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 模糊查询房屋合并/拆分变更列表;小区信息维护列表； 业主信息维护列表
     *
     * @param page  分页实体
     * @param param 模糊查询参数
     * @return 小区信息
     */
    @Override
    public PageInfo<BaseRegionInfo> fuzzyRegionSearch(Page page, String param) {
        //赋值区域,重要
        String zoneCode = zoneCodeUtil.getZoneCode();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> list = baseRegionInfoMapper.fuzzyRegionSearch(zoneCode, param);
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CommonResult updateStateById(String id, String state) {
        //包含自然幢不允许撤
        if (String.valueOf(NumberEnum.ZERO.getNum()).equals(state)) {
            //查询自然幢数量
            int count = baseBuildInfoMapper.getCountByRegionNo(id);
            if (count > NumberEnum.ZERO.getNum()) {
                return CommonResult.strResult(NumberEnum.ZERO.getNum(), "已存在自然幢信息！");
            }
        }
        int num = baseRegionInfoMapper.updateStateById(id, state);
        return CommonResult.ResponseResult(num);
    }

    /**
     * 小区名称不能重复  的 验证
     *
     * @param baseRegionInfoName
     * @return
     */
    @Override
    public CommonResult checkBaseRegionInfoName(String baseRegionInfoName, String id) {
        int ret = baseRegionInfoMapper.getCountByRegionName(baseRegionInfoName, null);
        if (ret > 0) {
            //如果数量大于0，表明数据库中存在该小区名称
            if (StringUtils.isEmpty(id)) {
                //如果ID为空，表明是新增
                return CommonResult.strResult(NumberEnum.ZERO.getNum(), "小区名称不能重复！");
            }
            //不为空，则表明是修改，查看是否是同一个小区的修改
            BaseRegionInfo info = getInfo(id);
            if (!baseRegionInfoName.equals(info.getRegionName())) {
                return CommonResult.strResult(NumberEnum.ZERO.getNum(), "小区名称不能重复！");
            }
        }
        return CommonResult.strResult(NumberEnum.ONE.getNum(), null);
    }

    @Override
    public PageInfo<BaseRegionInfo> getListToBatchRef(Page page, BaseRegionInfo baseRegionInfo) {
        baseRegionInfo.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> list = baseRegionInfoMapper.getListToBatchRef(baseRegionInfo);
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 模糊查询小区待审批列表
     *
     * @param page           分页实体
     * @param baseRegionInfo 查询实体
     * @return 待审核小区列表
     */
    @Override
    public PageInfo<BaseRegionInfo> fuzzyAuditList(Page page, BaseRegionInfo baseRegionInfo) {
        //查询业务   新增审核
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.REGION_INFO_ADD.getType());
        List<BaseRegionInfo> list = new ArrayList<>();
        if (null != map) {
            result.selectParm(map, baseRegionInfo);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = baseRegionInfoMapper.fuzzyAuditList(baseRegionInfo);
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseRegionInfo> selectByCommit(Page page, BaseRegionInfo baseRegionInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> baseRegionInfos = baseRegionInfoMapper.selectByCommit(baseRegionInfo);
        for (BaseRegionInfo b : baseRegionInfos) {
            if (StringUtils.isNotBlank(b.getZoneCode())) {
                ZoneCode zoneCode = zoneCodeMapper.getInfoByZoneCode(b.getZoneCode());
                b.setZoneCodeName(zoneCodeService.zoneName(zoneCode));
            }
        }
        PageInfo<BaseRegionInfo> pageInfo = new PageInfo<>(baseRegionInfos);
        return pageInfo;
    }
}
